package com.triumphxx.readingreminderbackend.service;

import com.triumphxx.readingreminderbackend.entity.Note;
import com.triumphxx.readingreminderbackend.entity.ReviewSchedule;
import com.triumphxx.readingreminderbackend.mapper.NoteMapper;
import com.triumphxx.readingreminderbackend.mapper.ReviewScheduleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author:triumphxx
 * @Date: 2025/11/20
 * @Time: 17:03
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: 笔记服务
 **/

@Service
public class NoteService {

    @Autowired
    private NoteMapper noteMapper;

    @Autowired
    private ReviewScheduleMapper reviewScheduleMapper;

    public List<Note> getAllNotes() {
        return  noteMapper.findAll();
    }

    public Optional<Note> findById(Long id) {
        return noteMapper.findById(id);
    }

    @Transactional
    public Note save(Note note) {
        if (note.getId() == null) {
            // 新增笔记
            note.setDbCreatedAt(LocalDateTime.now());
            note.setDbUpdatedAt(LocalDateTime.now());
            noteMapper.insert(note);

            // 计算并保存复习计划
            note.calculateReviewSchedules();
            if (note.getReviewSchedules() != null && !note.getReviewSchedules().isEmpty()) {
                reviewScheduleMapper.batchInsert(note.getReviewSchedules());
            }
        } else {
            // 更新笔记
            note.setDbUpdatedAt(LocalDateTime.now());
            noteMapper.update(note);
        }
        return note;
    }

    @Transactional
    public void delete(Long id) {
        // 先删除关联的复习计划
        reviewScheduleMapper.deleteByNoteId(id);
        // 再删除笔记
        noteMapper.delete(id);
    }

    public Optional<Note> findByYuqueUrl(String yuqueUrl) {
        return noteMapper.findByYuqueUrl(yuqueUrl);
    }

    public List<Note> getTodayReviews() {
        return noteMapper.findTodayReviews();
    }

    @Transactional
    public boolean completeReview(Long noteId, Integer stage) {
        Optional<ReviewSchedule> scheduleOpt = reviewScheduleMapper.findByNoteIdAndStage(noteId, stage);

        if (scheduleOpt.isPresent()) {
            ReviewSchedule schedule = scheduleOpt.get();
            schedule.setCompleted(true);
            schedule.setCompletedAt(LocalDateTime.now());
            reviewScheduleMapper.update(schedule);
            return true;
        }

        return false;
    }

    // 获取所有今天需要复习的笔记（用于定时任务）
    public List<ReviewSchedule> getAllTodayReviews() {
        return reviewScheduleMapper.findAllTodayReviews();
    }
}
